A BufferedOutputStream buffers output data for greater
efficiency.
We will get back to BufferedOutputStream in a while.
For now, look at the example program.
The FileOutputStream constructor
opens the file "intData.dat" for writing.
A new file is created; if an old file has the same name it will be
deleted.
Then a DataOutputStream is connected to
the FileOutputStream.
DataOutputStream has methods for
writing primitive data to a output stream.
The writeInt() method
writes the four bytes of an int datatype
to the stream.
import java.io.*;
class WriteInts
{
public static void main ( String[] args )
{
String fileName = "intData.dat" ;
int value0 = 0, value1 = 1,
value255 = 255, valueM1 = -1;
try
{
DataOutputStream out = new DataOutputStream(
new FileOutputStream( fileName ) );
out.writeInt( value0 );
out.writeInt( value1 );
out.writeInt( value255 );
out.writeInt( valueM1 );
out.close();
}
catch ( IOException iox )
{
System.out.println("Problem writing " + fileName );
}
}
}
The program writes four integers to the output stream and then closes the stream. Always close an output stream to ensure that the operating system actually writes the data.